import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10,
    total: 0,
    goodsList: [],
    isOver: false,
    isLoading: false
  }

  onLoad(options) {
    // console.log(options)
    this.query = options.query || ''
    this.cid = options.cid || ''
    this.getGoodsList()
  }

  methods = {
    goGoodDetail(goods_id){
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + goods_id
      })
    }
  }

  async getGoodsList(cb) {
    this.isLoading = true
    const { data: res } = await wepy.get('/goods/search', {
      query: this.query,
      cid: this.cid,
      pagenum: this.pagenum,
      pagesize: this.pagesize
    })
    if (res.meta.status !== 200) {
      return wepy.baseToast()
    }
    this.total = res.message.total
    this.goodsList = [...this.goodsList, ...res.message.goods]
    this.isLoading = false
    this.$apply()
    cb && cb()
  }

  onReachBottom(){
    if(this.isLoading){
      return
    }
    if(this.pagenum * this.pagesize >= this.total){
      this.isOver = true
      return
    }
    this.pagenum++
    this.getGoodsList()
  }

  onPullDownRefresh(){
    this.pagenum= 1
    this.total= 0
    this.goodsList= []
    this.isOver= false
    this.isLoading= false

    this.getGoodsList(() => {
      wepy.stopPullDownRefresh()
    })
  }
}
